package com.vipyinzhiwei.android.library;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.vipyinzhiwei.android.library.base.ui.IActivity;
import com.vipyinzhiwei.android.library.base.ui.IFragment;
import com.vipyinzhiwei.android.library.exception.AppCrashHandler;
import com.vipyinzhiwei.android.library.tools.uipage.DefaultIActivityImpl;
import com.vipyinzhiwei.android.library.tools.uipage.DefaultIFragmentImpl;

import java.lang.ref.WeakReference;
import java.util.Stack;

/**
 * @author vipyinzhiwei
 * @version 1.0
 */
public class MApplication extends Application {
    /**
     * 对外提供整个应用生命周期的Context
     **/
    private static Context instance;
    /**
     * 渠道ID
     **/
    public static String channelId = "vipyinzhiwei";
    /**
     * 应用程序版本versionName
     **/
    public static String version = "error";
    /**
     * 设备ID
     **/
    public static String deviceId = "error";
    /**
     * 寄存整个应用Activity
     **/
    private static final Stack<WeakReference<Activity>> activitys = new Stack<>();
    /**
     * 日志输出标志
     **/
    protected final String TAG = this.getClass().getSimpleName();

    public static Context gainContext() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        init();
    }

    //初始化相关
    private void init() {
        //注册崩溃异常处理类 TODO: 2018/7/25 创建文件时需动态申请写入权限
        AppCrashHandler.getInstance().register(this);

        try {
            //应用程序版本
            version = AppEnvironment.getVersionName();
            //设备ID
//			deviceId = AppEnvironment.DEVICE_ID;
            //获取渠道号
//			channelId = ToolChannel.gainChannel(this, ToolChannel.CHANNEL_KEY,"Ajava");

        } catch (Exception e) {
            Logger.e(TAG, "初始化设备ID、获取应用程序版本失败，原因：" + e.getMessage());
        }

        resetResources();

        setUiImpl(new DefaultIActivityImpl(),new DefaultIFragmentImpl());
    }

    /**
     * 保证APP字体不受用户调整手机字体大小而影响，确保布局不会变形，或者sp使用dp替代
     */
    protected void resetResources() {
        Resources res = super.getResources();
        if (res != null) {
            android.content.res.Configuration cfg = res.getConfiguration();
            if (cfg != null && cfg.fontScale != 1.0f) {
                cfg.fontScale = 1.0f;
                res.updateConfiguration(cfg, res.getDisplayMetrics());
            }
        }
    }

    /**
     * 获取网络是否已连接，使用该方法之前，记得在AndroidManifest.xml添加权限许可
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    public static boolean isNetworkReady() {
        try {
            ConnectivityManager connectivity =
                    (ConnectivityManager) instance.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 注入UI（Activity,Fragment）生命周期方法管理类，根据业务需求是否实现友盟统计功能。
     *
     * @param sIActivity
     */
    protected void setUiImpl(IActivity sIActivity, IFragment sIFragment) {

    }

    /*******************************************Application中存放的Activity操作（压栈/出栈）API（开始）*****************************************/

    /**
     * 将Activity压入Application栈
     *
     * @param task 将要压入栈的Activity对象
     */
    public void pushTask(WeakReference<Activity> task) {
        activitys.push(task);
    }

    /**
     * 将传入的Activity对象从栈中移除
     *
     * @param task
     */
    public void removeTask(WeakReference<Activity> task) {
        activitys.remove(task);
    }

    /**
     * 根据指定位置从栈中移除Activity
     *
     * @param taskIndex Activity栈索引
     */
    public void removeTask(int taskIndex) {
        if (activitys.size() > taskIndex)
            activitys.remove(taskIndex);
    }

    /**
     * 将栈中Activity移除至栈顶
     */
    public void removeToTop() {
        int end = activitys.size();
        int start = 1;
        for (int i = end - 1; i >= start; i--) {
            Activity mActivity = activitys.get(i).get();
            if (null != mActivity && !mActivity.isFinishing()) {
                mActivity.finish();
            }
        }
    }

    /**
     * 移除全部（用于整个应用退出）
     */
    public void removeAll() {
        //finish所有的Activity
        for (WeakReference<Activity> task : activitys) {
            Activity mActivity = task.get();
            if (null != mActivity && !mActivity.isFinishing()) {
                mActivity.finish();
            }
        }
    }

    /**
     * 退出整个APP，关闭所有activity/清除缓存等等
     */
    public void exit() {

    }

    /*******************************************Application中存放的Activity操作（压栈/出栈）API（结束）*****************************************/
}
